const util = require('../../utils/util.js');
const tool = require('../../utils/tool.js');

const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const selectStore = require('../../utils/selectStore.js');
const aiChatTools = require('../../utils/aiChatTools.js');


//获取应用实例
const app = getApp();

Page({
  data: {
    banner: [],
    list: []
  },

  onShareAppMessage: function () {
    return {
      title: '计费宝',
      desc: '专业计算公式',
      path: '/pages/index/index'
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getLinks();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },


  onLoad: function (options) {


    this.getAd();

  },

  onUnload: function () {

  },
  onShow: function () {
    this.getLinks();
  },

  handleMore: function () {
    wx.navigateTo({
      url: "/pages/moreCharge/index"
    });
  },

  selectItem(e) {
    user.getUserInfoServer().then(res => {

      const index = e.currentTarget.dataset.index;
      const id = e.currentTarget.dataset.id;
      selectStore.setSelectIndex(id);
      let list = this.data.list.map(item => {
        // 当前点击项：选中状态切换，其他项全部取消选中
        return {
          ...item,
          selected: item.id === id ? !item.selected : false
        }
      });

      this.setData({
        list
      });

      let currentItem = this.data.list[index];

      console.log(currentItem);
      //url
      if (!currentItem.isCalculate) {
        let url = currentItem.url + "?chargeId=" + id + "&token=" + user.getLoginToken();
        console.log(url);

        util.parseWebViewUrl(url);
      } else {
        this.goCalculateDetai(currentItem.id);
      }

    }).catch(err => {
      util.showErrorToast(err);
    });


  },

  selectItemBack(e) {

    user.getUserInfoServer().then(res => {
      let userInfo = user.getLoginUserInfo();
      let vipEnd = userInfo.vipEndDate;
      if (!vipEnd) {
        console.log("!vipEnd");
        wx.navigateTo({
          url: '/pages/ucenter/charge/index',
        })
      } else {
        let dateNow = new Date();
        if (!tool.compareDates(new Date(vipEnd), dateNow)) {
          wx.navigateTo({
            url: '/pages/ucenter/charge/index',
          })
        } else {
          const index = e.currentTarget.dataset.index;
          const id = e.currentTarget.dataset.id;
          selectStore.setSelectIndex(id);
          let list = this.data.list.map(item => {
            // 当前点击项：选中状态切换，其他项全部取消选中
            return {
              ...item,
              selected: item.id === id ? !item.selected : false
            }
          });

          this.setData({
            list
          });

          let currentItem = this.data.list[index];

          let url = currentItem.url;

          wx.navigateTo({
            url: `/pages/webview/index?url=${url}`
          });

          console.log(currentItem);
        }




      }




    }).catch(err => {
      util.showErrorToast(err);
    });


  },

  //首页链接
  getLinks() {
    try {
      let that = this;
      let indexId = selectStore.getSelectIndex();
      console.log(indexId);
      util.request(api.chargesCollectList, 'GET').then(function (res) {
        if (res.errno === 0) {
          let data = res.data;

          data.forEach(item => {
            item.selected = item.id == indexId ? true : false;
          });
          if (!indexId) {
            data[0].selected = true;
          }

          that.setData({
            list: data,
          })

        }

      }).catch(err => {

      });
    } catch (err) {
      console.error(err);
    }

  },

  //广告
  getAd() {
    try {
      let that = this;
      util.request(api.adList, {
        position: 1,
      }, 'GET').then(function (res) {
        if (res.errno === 0) {
          let data = res.data;
          that.setData({
            banner: data,
          })

        }

      }).catch(err => {

      });
    } catch (err) {
      console.error(err);
    }

  },
  /**计算公式 */
  goCalculateDetai(chargeId) {
    wx.navigateTo({
      url: `/pages/calculateCharge/index?chargeId=${chargeId}`,
    })
  }


})